<template>
  <WdConfigProvider :theme="theme" :theme-vars="themeVarsMap">
    <div
      class="defaul-app-layout min-h-100vh"
      :class="{ 'wot-theme-light': theme === 'light', 'wot-theme-dark': theme === 'dark' }"
      :style="{ ...cssVars }"
    >
      <view class="bg-bgPrimary color-textPrimary">
        <slot />
      </view>

      <wd-toast />
      <wd-message-box />
    </div>
  </WdConfigProvider>
</template>
<script setup lang="ts">
import { useTheme } from '@/hooks';
import { useToast, useMessage } from 'wot-design-uni';
import { initCssVars, themeConfig, themeConfigMapping } from '@/theme';
import type { ToastOptions } from 'wot-design-uni/components/wd-toast/types';
import type { MessageOptions } from 'wot-design-uni/components/wd-message-box/types';
const { theme, themeVars } = useTheme(themeConfig);
// 生成css 变量
const cssVars = computed(() => {
  return initCssVars(theme.value, themeVars.value);
});

// 自定义的theme 映射为 组件库主题
const themeVarsMap = computed(() => {
  return themeConfigMapping(themeVars.value);
});

type MessageType = 'show' | 'confirm' | 'alert' | 'prompt' | 'close';

interface MessageParams {
  type: MessageType;
  data: MessageOptions;
}

/**
 * 注册全局 message 事件
 */

const message = useMessage();

const handleMessage = (params: MessageParams) => {
  const { type, data } = params;
  if (typeof message[type] === 'function') {
    message[type](data);
  }
};

uni.$on('message', handleMessage);

/**
 * 注册全局触发toast 事件
 */
const toast = useToast();
type ToastType = 'success' | 'error' | 'info' | 'warning' | 'loading' | 'close';

interface ToastParams {
  type: ToastType;
  data: ToastOptions;
}
//toast 事件处理函数
const handleToast = (params: ToastParams) => {
  const { type, data } = params;
  if (typeof toast[type] === 'function') {
    toast[type](data);
  }
};

// 注册事件监听
uni.$on('toast', handleToast);

// 组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('toast', handleToast);
});
</script>
<style lang="scss"></style>
